//
//  UIViewController+Camera.m
//  LuxuryGoods
//
//  Created by 刘星辰 on 2018/5/19.
//  Copyright © 2018年 Future. All rights reserved.
//

#import "UIViewController+Camera.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import "LGAuthorityManager.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import <objc/runtime.h>


@interface UIViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>


@end

@implementation UIViewController (Camera)
- (void)addPhotoFromCameraAllowEdit:(BOOL)allowsEditing sucess:(void(^)(UIImage *image))sucess
{
    
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        return;
    }
    
    
    
    void(^camera)(void) = ^(void) {
        UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
        imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.modalPresentationStyle= UIModalPresentationFullScreen;
        imagePicker.delegate = self;
        imagePicker.allowsEditing = allowsEditing;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        //录制视频时长，默认10s
        imagePicker.videoMaximumDuration = 15;
        
        //相机类型（拍照、录像...）字符串需要做相应的类型转换
        imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
        
        //设置摄像头模式（拍照，录制视频）为录像模式
        imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
        
        [self presentViewController:imagePicker animated:YES completion:nil];
        
        objc_setAssociatedObject(self, @selector(takePhoto), sucess, OBJC_ASSOCIATION_COPY_NONATOMIC);
    };
    
    [LGAuthorityManager requestCameraAuthority:^(NSError *error) {
        if (error)
        {
            [SVProgressHUD showInfoWithStatus:@"请在iPhone的“设置-隐私-相机”选项中，允许本应用程序访问你的相机。"];
        }
        else
        {
            camera();
        }
    }];
    
    
    
    
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        NSString *key = nil;
        if (picker.allowsEditing)
        {
            key = UIImagePickerControllerEditedImage;
        }
        else
        {
            key = UIImagePickerControllerOriginalImage;
        }
        UIImage *image = [info objectForKey:key];
        if (picker.sourceType == UIImagePickerControllerSourceTypeCamera)
        {
            //保存到相册
            UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
            void(^sucess)(UIImage *image) = objc_getAssociatedObject(self, @selector(takePhoto));
            if (sucess)
            {
                sucess(image);
            }
            
        }
        [picker dismissViewControllerAnimated:YES completion:^{
            
        }];
    }
}

# pragma mark - 拍照处理
- (void)takePhoto
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        //先检查相机可用是否
        
        [LGAuthorityManager requestCameraAuthority:^(NSError *error) {
            if (error)
            {
                [self presentViewController:picker animated:YES completion:nil];
                
            }
            else
            {
                [SVProgressHUD showInfoWithStatus:@"请在iPhone的“设置-隐私-相机”选项中，允许本应用程序访问你的相机。"];
            }
        }];
        
    }
}
- (BOOL)checkCamera{
    NSString *mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if(AVAuthorizationStatusRestricted == authStatus ||
       AVAuthorizationStatusDenied == authStatus){
        return NO;//相机不可用
    }
    return YES;//相机可用
}

#pragma mark 图片保存完成响应
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (!error)
    {
        
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}

@end
